package com.pe.pgn.clubpgn.dao.impl;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Repository;

import com.pe.pgn.clubpgn.common.CLPConstantes;
import com.pe.pgn.clubpgn.dao.MetaDao;
import com.pe.pgn.clubpgn.dao.hibernate.GenericDaoHibernate;
import com.pe.pgn.clubpgn.domain.ClpbEstacion;
import com.pe.pgn.clubpgn.domain.ClpbPrograma;
import com.pe.pgn.clubpgn.domain.ClpdMeta;
import com.pe.pgn.clubpgn.model.User;

@Repository("metaDao")
public class MetaDaoImpl extends GenericDaoHibernate<ClpdMeta, Long> implements MetaDao{

	private JdbcTemplate jdbcTemplate;
	
	@Autowired
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}
	
	public MetaDaoImpl() {
		super(ClpdMeta.class);
	}

	@SuppressWarnings("unchecked")
	public ClpbPrograma findPrograma(Long coPrograma) {

		StringBuffer query = new StringBuffer();
		query.append(" select ");
		query.append(" 	 id, ");
		query.append("   de_programa as dePrograma ");
		query.append(" from clpb_programa  ");
		query.append(" where 1 = 1 ");
		query.append(" and id = ").append(coPrograma);
		
		List<ClpbPrograma> list = findListOfBeans(query.toString(), null, ClpbPrograma.class);
		return (ClpbPrograma)list.get(0);
	}

	public List<Map<String, Object>> metasPorProgramas(Long coPrograma) {

		try{
			
			StringBuffer query=new StringBuffer();
			query.append(" select id as id, ");
			query.append(" va_costo  as vaCosto, ");
			query.append(" va_meta   as vaMeta, ");
			query.append(" de_meta   as deMeta ");
			query.append(" from clpd_meta ");
			query.append(" where clpb_programa = "+coPrograma);
			query.append(" and st_meta = '"+CLPConstantes.ST_VERDADERO+"'");
			query.append(" order by va_meta");
			
			return jdbcTemplate.queryForList(query.toString()); 
			
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	public void eliminarMeta(Long idMeta) {

		remove(idMeta);
		getHibernateTemplate().flush();
	}

	public void saveOrUpdateMeta(ClpdMeta meta) {

		Long idMeta = meta.getId();
		if(idMeta == null){
			
			meta.setStMeta(true);
			meta.setCoUsuarioCreador(getUsuarioLogueado().getUsername());
			meta.setDaFechaCreacion(Calendar.getInstance());
		}else{
			
			meta.setStMeta(true);
			meta.setCoUsuarioModificador(getUsuarioLogueado().getUsername());
			meta.setDaFechaModificacion(Calendar.getInstance());
		}
		
		getHibernateTemplate().saveOrUpdate(meta);
		getHibernateTemplate().flush();	
	}
	
}
